package com.ht.module.common.controller;

import cn.hutool.core.util.StrUtil;
import com.ht.config.properties.WeixinProperties;
import com.ht.module.sys.service.ISysUserService;
import com.ht.util.EncryptionUtil;
import com.ht.util.JsonResult;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @ClassName ThreeCertificationController
 * @Description TODO（微信相关接口）
 * @Author hejialun
 * @Date 2022/12/6 16:58
 * @Version 1.0
 */
@RestController
@RequestMapping("/weixin")
@Api(tags = "微信相关接口 ")
@Slf4j
public class WeixingController {
    @Resource
    private WeixinProperties weixinProperties;

    @Resource
    private ISysUserService sysUserService;

    @GetMapping(value = "/login")
    public JsonResult Login(@RequestParam(value = "code")String code,@RequestParam(value = "state")String state) throws Exception {
        // 查看获取到的code
        log.info("进入微信登入方法，code为：{}, state为：{}",code,state);
        return JsonResult.success();
    }


    /**
     * 验证微信消息
     *
     * @param request
     * @return
     */
    @GetMapping(value = "/check")
    public String checkWxMsg(HttpServletRequest request) {
        log.info("进入微信校验的接口了");
        /**
         * 微信加密签名
         */
        String signature = request.getParameter("signature");
        /**
         * 随机字符串
         */
        String echostr = request.getParameter("echostr");
        /**
         * 时间戳
         */
        String timestamp = request.getParameter("timestamp");
        /**
         * 随机数
         */
        String nonce = request.getParameter("nonce");

        List<String> strs=new ArrayList<>();
        strs.add(timestamp);
        strs.add(nonce);
        strs.add(weixinProperties.getToken());
        //将token、timestamp、nonce三个参数进行字典序排序
        strs=strs.stream().filter(StrUtil::isNotEmpty).sorted().collect(Collectors.toList());
        StringBuffer sb = new StringBuffer();
        //将三个参数字符串拼接成一个字符串进行sha1加密
        for (String param:strs) {
            sb.append(param);
        }
        //获取到加密过后的字符串
        String encryptStr = EncryptionUtil.encrypt(sb.toString(),"sha-1");
        //判断加密后的字符串是否与微信的签名一致
        if(StrUtil.equalsIgnoreCase(signature,encryptStr)){
            log.info("签名一致可以通过");
            return echostr;
        }
        log.error("这不是微信发来的消息！！");
        return null;
    }


}
